<?php

class field_menuComponents extends sfComponents
{ 
  
  private $rootMenuId = 1;
  
  private $culture = 'pl';
  
  private $menuSeries = array();
  
  public $menu = array();

  public function executeMenu(sfWebRequest $request)
  {    
      $this->culture = $request->getParameter('sf_culture');
    
      $table = $request->getParameter('table');
      
      if($table)
      {
        $q = Doctrine_Core::getTable(sfConfig::get('app_soulution_name') . 'FieldMenu')->createQuery('c');
    
        $menus = $q->select('c.id')->where('c.module = ?', $table)->execute()->toArray();
        
        $moduleId = $menus[0]['id'];
      }
      else
      {
        $moduleId = 1;
      }
    
      $this->setMenuSeries($moduleId);
      $this->getMenuTree();
      
      $this->menuLevels = $this->menu; 
  }
  
  private function getMenuTree($key = 0, $level = 0)
  {
      if(isset($this->menuSeries[$key]))
      {
        $menuId = $this->menuSeries[$key];

        $q = Doctrine_Core::getTable(sfConfig::get('app_soulution_name') . 'FieldMenu')->createQuery('c');

        $andSelect = null;

        if(isset($this->menuSeries[$key+1]))
        {
            $nextMenuId = $this->menuSeries[$key+1];
            $andSelect = ",IF(c.id = $nextMenuId, 1, 0) as marked";
        }

        $q->select('c.*, t.*' . $andSelect)
          ->leftJoin('c.Translation t')
          ->where('c.parent_id = ?', $menuId)
          ->andWhere('c.is_active = ?', true)
          ->andWhere('t.lang = ?', $this->culture)
          ->orderBy('c.position ASC');

        $children = $q->execute()->toArray();

        if($children)
        {
          $this->menu[$level] = $children;
        }

        $this->getMenuTree(++$key, ++$level);          
      }
    }
    
    private function setMenuSeries($parentMenuId)
    {
      $this->menuSeries[] = $parentMenuId;
      if($parentMenuId > $this->rootMenuId)
      {
        $q = Doctrine_Core::getTable(sfConfig::get('app_soulution_name') . 'FieldMenu')->createQuery('c');
        $array = $q->select('c.parent_id')->where('c.id = ?',$parentMenuId)->execute()->toArray();
        $this->setMenuSeries($array[0]['parent_id']);
      }
      else
      {
        $this->menuSeries = array_reverse($this->menuSeries);
      }
    }
}